//
//  MyInformationService.swift
//  ezyform
//
//  Created by MoennigQ on 19/02/2017.
//  Copyright © 2017 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SwiftyJSON
import HandyJSON
import Alamofire
class MyInformationService: BaseService {
    
    func getMyInformation(){
        
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.MyInformationAPI)
        
        let alRequest = ALRequest.init(mainURL: url, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj,_) -> Void in
            
            if let result = obj {
                let json = JSON(result)
                let modeStr = json.rawString()
                let model = JSONDeserializer<MyInformationModel>.deserializeFrom(json: modeStr) ?? MyInformationModel()
                APPConfig.loginInfo.effective_date = model.effective_date
                self.returnBlock(model,nil)
            }else{
                self.returnBlock(nil,nil)
            }
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest(cacheFlag: true)
    }
    
    func resetPassword(_ model: MyInformationModel){
        
        let params: Parameters = ["password": model.oldPassword, "new_password" : model.newPassword,"new_password_confirmation": model.confirmNewPassword ]
        
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.ResetPasswordAPI)
        
        let alRequest = ALRequest.init(mainURL: url, method: .put, headers: RequestConstant.AuthTokenParam, paramDict: params, successBlock: { (obj,_) -> Void in
            
            let json = JSON(obj!)
            let modeStr = json.rawString()
            
            let model = JSONDeserializer<MyInformationModel>.deserializeFrom(json: modeStr)
            
            self.returnBlock(model,nil)
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
    
    func uploadAvatarImage(_ imageData: Data){
        let urlStr = APIConfig.getRequestAPIForV2(APIConfig.UploadAvatarImage)
        netmanagerForUpload.upload(multipartFormData: { (formData) in
            formData.append(imageData, withName: "avatar",fileName: "avatar" + APPConfig.ImageSuffix, mimeType: "image/png")
        }, to: urlStr, method: HTTPMethod.post, headers: RequestConstant.AuthTokenParam).responseData { resp in
            switch resp.result {
            case .success(let data):
                do {
                    //只要符合String.Encoding.utf8这种编码的data都能转化成功,确认是返回数据结构是否正常
//                    let jsonString = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
                    let asJSON = try JSONSerialization.jsonObject(with: data)
                    if let dic = asJSON as? NSDictionary{
                        if let successFlag = dic.object(forKey: "result") as? Bool,successFlag {//success
                            if let obj = dic.object(forKey: "data"){
                                let json = JSON(obj)
                                
                                let model = JSONDeserializer<MyInformationModel>.deserializeFrom(json: json.rawString())
                                self.returnBlock(model,nil)
                            }
                            
                        }else{//error
                            var errMsg = ""
                            var errCode = ""
                            if let data = dic.object(forKey: "code") as? Int{
                                errCode = "\(data)"
                            }
                            if let msg = dic.object(forKey: "msg") as? String{
                                errMsg = msg
                            }
                            self.errorBlock(errCode,errMsg)
                            
                        }
                    }else{
                        self.errorBlock("", "response.value is not dictionary of \(APIConfig.UploadAvatarImage)")
                    }
                } catch (let error){
                    let errorMsg = APPConfig.isTestFlag ? ("Convert data to JSON failed: " + urlStr + "\n params: \(RequestConstant.AuthTokenParam)") : error.localizedDescription
                    self.errorBlock?("",errorMsg)
                    // Here, I like to keep a track of error if it occurs, and also print the response data if possible into String with UTF8 encoding
                    // I can't imagine the number of questions on SO where the error is because the API response simply not being a JSON and we end up asking for that "print", so be sure of it
//                    print("Error while decoding response: "\(error)" from: \(String(data: data, encoding: .utf8))")
                }
            case .failure(_):
                self.errorBlock?("",RequestErrorType.NetworkError.rawValue)
            }
        }
    }
    func getJobsCntAndReward(){
        
        let url : String = APIConfig.getRequestAPIForV2(APIConfig.GetJobsCntAndReward)
        
        let alRequest = ALRequest.init(mainURL: url, method: .get, headers: RequestConstant.AuthTokenParam, paramDict: nil, successBlock: { (obj, _) -> Void in
            
            if let result = obj {
                let json = JSON(result)
                let modeStr = json.rawString()
                
                let model = JSONDeserializer<JobsCntAndReward>.deserializeFrom(json: modeStr)
                
                self.returnBlock(model,nil)
            }else{
                self.returnBlock(nil,nil)
            }
            
        }) {(code, obj) -> Void in
            self.errorBlock?(code, obj)
        }
        alRequest.startRequest()
    }
}
